@file:Suppress("SetTextI18n")

package com.jiangyan.hookplus.ui.activity

import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.view.Gravity
import android.view.ViewGroup
import android.widget.*
import androidx.core.view.isVisible
import com.highcapable.yukihookapi.YukiHookAPI
import com.highcapable.yukihookapi.hook.log.loggerD
import com.highcapable.yukihookapi.hook.log.loggerE
import com.jiangyan.hookplus.BuildConfig
import com.jiangyan.hookplus.R
import com.jiangyan.hookplus.databinding.ActivityMainBinding
import com.jiangyan.hookplus.ui.activity.base.BaseActivity
import com.jiangyan.hookplus.common.MethodTool
import com.jiangyan.hookplus.common.Request
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.PopNotification
import com.kongzue.dialogx.dialogs.PopTip
import kotlin.system.exitProcess


class MainActivity : BaseActivity<ActivityMainBinding>() {


    override fun onCreate() {
        refreshModuleStatus()
        binding.mainTextVersion.text = getString(R.string.module_version, BuildConfig.VERSION_NAME)
        binding.hideIconInLauncherSwitch.isChecked = isLauncherIconShowing.not()
        binding.hideIconInLauncherSwitch.setOnCheckedChangeListener { button, isChecked ->
            if (button.isPressed) hideOrShowLauncherIcon(isChecked)

        }
        //添加网络请求权限
        val policy = ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
        //初始化DiaLogX组件
        DialogX.init(this);

        loggerD("检查", "版本是${getVersionName()}")
        //弹出公告
        MethodTool().announcement()
        //检查软件更新
        updateApp()

        binding.tvFanqiexiaoshuo.setOnClickListener {
            //调用有道云笔记
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("番茄免费小说", nestedValue, "com.dragon.read", "5.8.9.32", "解锁会员功能")
        }
        //检查更新
        binding.btnShowBottomSheet.setOnClickListener {
            updateApp()
        }
        binding.tvMaqueji.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("麻雀记", nestedValue, "com.chrissen.card", "4.9.1", "解锁会员功能")
        }
        binding.tvMt.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("MT管理器", nestedValue, "bin.mt.plus", "未知", "解锁会员部分功能")
        }
        binding.tvYuedu.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("阅读", nestedValue, "io.legado.app.release", "全版本", "解除源禁")
        }
        binding.tvTg.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("Telegram", nestedValue, "org.telegram.messenger", "全版本", "解锁会员功能")
        }

        binding.tvHook.setOnClickListener {
            //Hook投稿
            val uri = Uri.parse("https://qm.qq.com/cgi-bin/qm/qr?k=F9Vxxdy8oCUNZaeeQ30LMBEq6cSFO1yY")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }

        binding.tvQimao.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("七猫免费小说", nestedValue, "com.kmxs.reader", "7.31", "解锁会员功能")
        }

        binding.tvTaoxiaoshuo.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("淘小说", nestedValue, "com.martian.ttbook", "9.4.0", "解锁会员功能")
        }

        binding.tvZuiyou.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("最右", nestedValue, "cn.xiaochuankeji.tieba", "5.13.11", "强去广告")
        }
        binding.tvFanqiechangting.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("番茄畅听", nestedValue, "com.xs.fm", "5.0.6.32", "解锁会员功能 去广告")
        }
        binding.tvHuluxia.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("葫芦侠虚拟机", nestedValue, "com.huluxia.vm", "1.1.0", "解锁会员功能")
        }
        binding.tvYunji.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("云记", nestedValue, "com.jideos.jnotes", "2.8.3.2", "解锁会员功能")
        }
        binding.tvFakelocation.setOnClickListener {
            val nestedValue = Request().getListValue(
                "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=a368a26df9f9e302891d31f0bd37e0a9&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=pkCDjIlI"
            )
            //拉取数据传入列表内
            showPopup("Fake Location", nestedValue, "com.lerist.fakelocation", "1.3.2.2", "解锁会员部分功能")
        }
    }

    /**
     * 封装弹窗函数（标题、列表、列表点击下载、取消按钮）
     * title:标题
     * items：列表数据
     * appversion：适配版本
     * Description：功能描述
     * **/
    private fun showPopup(
        title: String, items: List<Pair<String, String>>, pgnm: String, appversion: String, description: String
    ) {
        loggerD("日志:", " 传入查看结果$items")
        //创建弹窗
        val popupWindow = PopupWindow(this)
        popupWindow.animationStyle = R.style.PopupAnimation
        // 创建一个圆角矩形的形状
        val shape = GradientDrawable().apply {
            cornerRadius = 32F // 设置圆角的半径，可以根据需要进行调整
            setColor(Color.WHITE) // 设置背景颜色
        }

        //创建布局
        val layout = LinearLayout(this)
        val layoutApp = LinearLayout(this)
        val layoutApp1 = LinearLayout(this)
        //设置布局为垂直
        layout.orientation = LinearLayout.VERTICAL
        layoutApp.orientation = LinearLayout.HORIZONTAL
        layoutApp1.orientation = LinearLayout.VERTICAL
        layoutApp.setPadding(5, 20, 0, 20)
        val imageView = ImageView(this)
        imageView.setImageResource(R.mipmap.ic_launcher)

        //创建标题
        val titleTextView = TextView(this)
        titleTextView.text = title
        titleTextView.textSize = 20f
        titleTextView.setPadding(10, 20, 0, 20)
        titleTextView.gravity = Gravity.CENTER

        val titlename = TextView(this)
        val titlename1 = TextView(this)
        val titlename2 = TextView(this)
        titlename.text = "功能说明: $description"
        titlename1.text = "安装状态: 未安装  适配版本: $appversion"
        titlename2.text = "包名: $pgnm   当前版本号: 未知"
        titlename.setPadding(12, 0, 0, 10)
        titlename1.setPadding(12, 10, 0, 10)
        titlename2.setPadding(12, 10, 0, 10)
        //获取APP应用信息
        val packageManager = applicationContext.packageManager
        try {
            val packageInfo = packageManager.getPackageInfo(pgnm, 0)
            val appIcon = packageInfo.applicationInfo.loadIcon(packageManager)
            val versionName = packageInfo.versionName
            titlename.text = "功能说明: $description"
            titlename1.text = "安装状态: 已安装  适配版本: $appversion"
            titlename2.text = "包名: $pgnm   当前版本号: $versionName"
            imageView.setImageDrawable(appIcon)
        } catch (e: PackageManager.NameNotFoundException) {
            loggerE("HookPluse", "未找到包名:$pgnm", e)
        }


        //创建列表
        val listView = ListView(this)
        val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, getTitles(items))
        listView.adapter = adapter
//        listView.divider = null
        listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            val selectedItem = items[position]
            //获取链接跳转到浏览器下载
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(selectedItem.second))
            val aa = selectedItem.second
            loggerD("日志:", " 点击查看结果$aa")
            loggerD("日志:", " 点击查看链接结果$intent")
            if (aa.contains("htt")) {
                startActivity(intent)
            } else {
                Toast.makeText(
                    this, "没有获取到下载地址,请及时反馈", Toast.LENGTH_SHORT
                ).show()
            }
        }
        //取消
        val textButton = TextView(this).apply {
            setTextColor(Color.GRAY)
        }
        textButton.text = "取消"
        textButton.textSize = 18f
        textButton.setPadding(0, 20, 0, 0)
        textButton.gravity = Gravity.CENTER
        textButton.setOnClickListener {
            popupWindow.dismiss()
        }



        layout.addView(
            titleTextView,
            LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        )
        layout.addView(
            layoutApp,
            LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        )
        layout.addView(
            listView,
            LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        )
        layout.addView(
            textButton,
            LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        )
        layoutApp.addView(imageView, 200, 200)
        layoutApp.addView(layoutApp1)
        layoutApp1.addView(titlename)
        layoutApp1.addView(titlename1)
        layoutApp1.addView(titlename2)

        //设置弹窗属性
        popupWindow.contentView = layout
        popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
        popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow.isOutsideTouchable = true
        popupWindow.isFocusable = true
        popupWindow.animationStyle = R.style.PopupAnimation
        popupWindow.setBackgroundDrawable(shape)

        // 显示弹窗
        popupWindow.showAtLocation(layout, Gravity.BOTTOM, 0, 0)
    }

    //获取版本号
    private fun getVersionName(): String {
        return try {
            val packageInfo = packageManager.getPackageInfo("com.jiangyan.hookplus", 0)
            val versionName = packageInfo.versionName
            versionName
        } catch (e: PackageManager.NameNotFoundException) {
            loggerE("HookPluse", "未找到包名:", e)
            "获取版本号报错了"
        }

    }

    //检查更新
    private fun updateApp() {
        val updateUrl =
            "https://note.youdao.com/yws/api/personal/share?method=get&shareKey=5c77e902cffd64d8c1b47c46f6f1c229&unloginId=e2a73838-3dbe-67e3-58bf-2ec63e74d542&sec=v1&cstk=kx5YQrx-\n"
        val nestedValue = Request().getListValue(updateUrl)
        if (nestedValue[1].first > getVersionName()) {
            MessageDialog.show(nestedValue[0].first, nestedValue[0].second, "确定").setOkButton { _, _ ->
                PopTip.show("跳入下载地址")
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(nestedValue[1].second))
                startActivity(intent)
                android.os.Process.killProcess(android.os.Process.myPid())    //获取PID
                exitProcess(0)
            }.setCancelable(false)
        } else {
            PopNotification.show("目前已经是最新版啦！")
        }
    }


    /**
     * 返回所有项目的标题的列表。
     * **/
    private fun getTitles(items: List<Pair<String, String>>): List<String> {
        return items.map { it.first }
    }

    /**
     * 隐藏或显示启动器图标
     * - 你可能需要 LSPosed 的最新版本以开启高版本系统中隐藏 APP 桌面图标功能
     * @param isShow Whether to display / 是否显示
     */
    private fun hideOrShowLauncherIcon(isShow: Boolean) {
        packageManager?.setComponentEnabledSetting(
            ComponentName(packageName, "${BuildConfig.APPLICATION_ID}.Home"),
            if (isShow) PackageManager.COMPONENT_ENABLED_STATE_DISABLED else PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP
        )
    }

    /**
     * 获取启动器图标状态
     * @return [Boolean] Whether to display / 是否显示
     */
    private val isLauncherIconShowing
        get() = packageManager?.getComponentEnabledSetting(
            ComponentName(packageName, "${BuildConfig.APPLICATION_ID}.Home")
        ) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED

    /**
     * 刷新模块状态
     */
    private fun refreshModuleStatus() {
        binding.mainLinStatus.setBackgroundResource(
            when {
                YukiHookAPI.Status.isModuleActive -> R.drawable.bg_green_round
                else -> R.drawable.bg_dark_round
            }
        )
        binding.mainImgStatus.setImageResource(
            when {
                YukiHookAPI.Status.isModuleActive -> R.mipmap.ic_success
                else -> R.mipmap.ic_warn
            }
        )
        binding.mainTextStatus.text = getString(
            when {
                YukiHookAPI.Status.isModuleActive -> R.string.module_is_activated
                else -> R.string.module_not_activated
            }
        )
        binding.mainTextApiWay.isVisible = YukiHookAPI.Status.isModuleActive
        binding.mainTextApiWay.text =
            if (YukiHookAPI.Status.Executor.apiLevel > 0) "Activated by ${YukiHookAPI.Status.Executor.name} API ${YukiHookAPI.Status.Executor.apiLevel}"
            else "Activated by ${YukiHookAPI.Status.Executor.name}"
    }
}